<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" scroll max-height="600px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :span="24">
        <el-col :span="12">
          <el-form-item label="资源名称" prop="sourceData.sourceName">
            <div style="width: 100%" @click="detailSourceSelectVisible = true">
              <el-input v-model="formData.sourceData.sourceName" placeholder="请选择资源" readonly />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源编号" prop="sourceData.sourceCode">
            <el-input v-model="formData.sourceData.sourceCode" placeholder="自动带出" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源类型" prop="sourceData.sourceType">
          <el-select v-model="formData.sourceData.sourceType" placeholder="自动带出" disabled>
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.SOURCE_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="来源信息" prop="sourceData.sourceDesc">
            <el-select v-model="formData.sourceData.sourceDesc" placeholder="自动带出" disabled>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SOURCE_DESC)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文件类型" prop="sourceData.fileType">
            <el-select v-model="formData.sourceData.fileType" placeholder="自动带出" disabled>
              <el-option
                v-for="dict in fileExtsList"
                :key="dict"
                :label="dict"
                :value="dict"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文件大小" prop="sourceData.fileSize">
            <el-input v-model="formData.sourceData.fileSize" placeholder="自动带出" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源封面" prop="sourceData.mainImage">
            <UploadImg v-model="formData.sourceData.mainImage" disabled width="56px" height="56px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源文件" prop="sourceData.file">
            <UploadFile
              v-model="formData.sourceData.file"
              :limit="1"
              :fileType="fileExtsList"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">创作者信息</el-divider>
      <el-row :span="24">
        <el-col :span="12">
          <el-form-item label="作者名称" prop="authorName">
            <el-input v-model="formData.authorName" placeholder="请输入作者名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="其它贡献者" prop="contributeName">
            <el-input v-model="formData.contributeName" placeholder="请输入其它贡献者" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="生平简介" prop="authorDesc">
            <!-- <el-input v-model="formData.authorDesc" placeholder="请输入生平简介" clearable /> -->
            <Editor
              v-model="formData.authorDesc"
              placeholder="请输入生平简介"
              :height="200"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">内容描述</el-divider>
      <el-row :span="24">
        <el-col :span="12">
          <el-form-item label="资源标签" prop="catalogTags">
            <el-tree-select
              v-model="formData.catalogTags"
              :data="tagList"
              :props="{
                label: 'tagName',
                value: 'id',
                children: 'children',
                disabled: (node) => node.children && node.children.length > 0,
              }"
              :render-after-expand="false"
              multiple
              check-on-click-node
              collapse-tags
              filterable
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="主题分类" prop="catalogClassify">
            <el-select
              v-model="formData.catalogClassify"
              placeholder="请选择主题分类"
              clearable
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.JOURNAL_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="资源描述" prop="catalogDesc">
            <!-- <el-input v-model="formData.catalogDesc" placeholder="请输入资源描述" clearable /> -->
            <Editor
              v-model="formData.catalogDesc"
              placeholder="请输入资源描述"
              :height="200"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">关联信息</el-divider>
      <el-row :span="24">
        <el-col :span="12">
          <el-form-item label="存放位置" prop="catalogStore">
            <el-input v-model="formData.catalogStore" placeholder="请输入存放位置" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="网络连接" prop="webUrl">
            <el-input v-model="formData.webUrl" placeholder="请输入网络连接" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参考书目" prop="attach">
            <el-input v-model="formData.attach" placeholder="请输入参考书目" clearable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="submitForm('save')" type="primary" :disabled="formLoading">暂 存</el-button>
      <el-button @click="submitForm('submit')" type="primary" :disabled="formLoading">提 交</el-button>
    </template>

    <!-- 标签选择弹窗 -->
    <SourceTagSelectDialog
      v-model:visible="detailSourceSelectVisible"
      v-model="formSourceList"
      :multiple="false"
      @submit="onChangeSource"
    />
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, fileExtsList, DICT_TYPE } from '@/utils/dict'
import { handleTree } from '@/utils/tree'
import { SourceApi, SourceVO } from '@/api/dr/source'
import { SourceCataApi, SourceCataVO } from '@/api/dr/sourcecata'
import { SourceTagApi, SourceTagVO } from '@/api/dr/sourcetag'

/** 资源信息 表单 */
defineOptions({ name: 'SourceCataForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const tagList = ref<SourceTagVO[]>([])
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formSourceList = ref<SourceVO[]>([])
const detailSourceSelectVisible = ref<boolean>(false)
const formData = ref<any>({
  id: undefined,
  sourceId: undefined,
  sourceData: {},
  fileType: undefined,
  fileSize: undefined,
  mainImage: undefined,
  file: undefined,
  sourceFrom: undefined,
  sourceStatus: undefined,
  catalogTags: [],
})
const formRules = reactive({
  catalogClassify: [
    { required: true, message: '请选择', trigger: ['blur', 'change'] },
  ],
  'sourceData.sourceName': [
    { required: true, message: '请选择', trigger: ['blur', 'change'] },
  ],
  'sourceData.sourceCode': [
    { required: true, message: '请输入', trigger: ['blur', 'change'] },
  ],
})
const formRef = ref() // 表单 Ref
/** 查询tag列表 */
const getTagList = async () => {
  try {
    const data = await SourceTagApi.getSourceTagPage({
      pageNo: 1,
      pageSize: 100,
    })
    data.list.forEach(v => {
      v.id = v.id + ''
    })
    tagList.value = handleTree(data.list, 'id', 'parentId', 'children')
  } finally {
  }
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await SourceCataApi.getDetail(id)
      formData.value = {
        ...data,
        authorDesc: data.authorDesc || '',
        catalogDesc: data.catalogDesc || '',
        catalogTags: data.catalogTags?.split(','),
        sourceData: {
          file: ''
        }
      }
      if(type === 'create' && id) {
        delete formData.value.id
      }
      if(formData.value.sourceId) {
        const sourceData = await SourceApi.getSource(formData.value.sourceId)
        formSourceList.value = [sourceData]
        formData.value.sourceData = {
          ...sourceData,
          file: sourceData.file || ''
        }
      }
    } finally {
      formLoading.value = false
    }
  }
  getTagList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type?:string) => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data: SourceCataVO | any = {
      ...formData.value,
      catalogTags: formData.value.catalogTags?.join(',')
    }
    data.operateFlag = type
    if (formType.value === 'create') {
      await SourceCataApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await SourceCataApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    sourceId: undefined,
    sourceData: {},
    sourceName: undefined,
    sourceCode: undefined,
    sourceType: undefined,
    sourceDesc: undefined,
    fileType: undefined,
    fileSize: undefined,
    mainImage: undefined,
    file: undefined,
    sourceFrom: undefined,
    sourceStatus: undefined,
    catalogTags: [],
  }
  formRef.value?.resetFields()
}
/** 选择文件 */
const onChangeSource = () => {
  // console.log(formSourceList.value)
  if (formSourceList.value && formSourceList.value.length > 0) {
    formData.value = {
      ...formData.value,
      sourceId: formSourceList.value[0]?.id,
      sourceData: formSourceList.value[0] || {},
    }
  }
}
</script>